package ru.adhoc.truealarm.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.SpannableString;
import android.text.format.DateFormat;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import ru.adhoc.truealarm.R;
import ru.adhoc.truealarm.alarmreceiver.AlarmManagerBroadcastReceiver;
import ru.adhoc.truealarm.db.DbHelper;
import ru.adhoc.truealarm.notification.NfHelper;
import ru.adhoc.truealarm.player.SoundPlayer;
import ru.adhoc.truealarm.time.TimeHelper;
import ru.adhoc.truealarm.utils.Constants;
import ru.adhoc.truealarm.utils.Util;


/**
 * Created by Малюгин Сергей on 17.06.13.
 */

public class MainActivity extends Activity implements View.OnClickListener, View.OnLongClickListener {

    private String LOG_TAG = "My";
    private DbHelper DbHelper;
    private NfHelper NfHelper;
    private LinearLayout LL;
    private AlarmManagerBroadcastReceiver alarm;
    private Context ctx;
    private boolean is24HourFormat;
    private LinearLayout llParent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ctx = this.getApplicationContext();

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        boolean hold = sp.getBoolean("hold", false);
        boolean classic = sp.getBoolean("classicOff",true);

        llParent = (LinearLayout)findViewById(R.id.llparent);
        Util.getInstance(ctx).setTheme(llParent);

        if(!classic){
            if(Constants.getInstance(this).alarmed && hold){

                Intent cancelAlarm = Util.getInstance(this).getActualCancelAlarmIntent();
                cancelAlarm.putExtra("id", Constants.getInstance(this).alarmedID);
                cancelAlarm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(cancelAlarm);
                finish();
            }
        }

        DbHelper = DbHelper.getInstance(this);
        NfHelper = NfHelper.getInstance(this);
        LL = (LinearLayout)findViewById(R.id.llscroll);
        alarm = new AlarmManagerBroadcastReceiver();
        is24HourFormat = DateFormat.is24HourFormat(this);

        fillAlarmTable();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main_pl, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case R.id.actBAdd:
                Intent intentSetAlarm = new Intent(this, SetAlarm.class);
                intentSetAlarm.putExtra("type_set",0); //0 - для создания нового будильника
                startActivity(intentSetAlarm);
                break;
            case R.id.menu_settings:
                Intent settingsActivity = new Intent(this, SettingsActivity.class);
                startActivity(settingsActivity);
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        //адйшники свичеров на 1000 больше чем у текст вьюшек
        int id = view.getId();
        //Log.d(LOG_TAG, "Click id = " + id);
        if(id < 1000) editAlarm(id);
        else switchAlarm(id - 1000);
    }

    //on/off alarm
    private void switchAlarm(int id){

        //Получаем текущее положение переключателя и дата/время будильника
        SQLiteDatabase db = DbHelper.getWritableDatabase();
        int sw = 0;

        try {
            Cursor c = DbHelper.getOnesAlarm(db,id);
            if(c.moveToFirst()){
                sw = c.getInt(c.getColumnIndex("switch"));
            }
            c.close();
        }
        finally {
            if(db != null)
                db.close();
        }



        Long actTimeNew = 0L;

//меняем переключатель и включаем или выключаем будильник
        if (sw == 0) {
            setSwitch(id,1);
            if(alarm != null){
                actTimeNew = TimeHelper.getInstance(ctx).getActualTimeForAlarmByID(id);
                refreshAlarmTime(actTimeNew, id);
                operationsToOnAlarm(actTimeNew,id);
            }
        }
        else {
            setSwitch(id,0);
            if(alarm != null)
                operationsToOffAlarm(id);
            //refreshNotification();
        }
    }

    private void setSwitch(int id, int status){

        SQLiteDatabase db = DbHelper.getWritableDatabase();
        try {
            DbHelper.setSwitch(db, id, status);
        }
        finally {
            if(db != null)
                db.close();
        }
    }

    //обновляем время будильника в базе
    private void refreshAlarmTime(Long time, int id){
        SQLiteDatabase db = DbHelper.getWritableDatabase();
        try {
            DbHelper.refreshAlarmTime(db, time, id);
        } catch (SQLException e) {
            Log.e(LOG_TAG, "Error while refreshing time alarm", e);
        } finally {
            if(db != null)
                db.close();
        }
    }

    //open set_alarm activity
    private void editAlarm(int id){
        Intent intentEditAlarm = new Intent(this, SetAlarm.class);
        intentEditAlarm.putExtra("type_set",id); //id =  ид текущего будильника, если передать 0 то это создание нового
        startActivity(intentEditAlarm);
    }

    //get data to build activity
    private void fillAlarmTable(){

        SQLiteDatabase db = DbHelper.getWritableDatabase();
        Cursor c = DbHelper.getAlarms(db);
        //Log.d(LOG_TAG, "--- size  --- = " + c.getCount());

        //проверяем версю андройда елси это 2-й и нет ещё созданных будильников даём справку
        if(c.getCount() == 0 && Util.getInstance(ctx).androidVersionCode() <= 2){
           showInfoToast();
        }

        if(c.moveToFirst())
        {
            int indtime = c.getColumnIndex("time");
            int indposition = c.getColumnIndex("position");
            int indswitch = c.getColumnIndex("switch");
            int indComment = c.getColumnIndex("comment");
            int indId = c.getColumnIndex("id");

            do
            {
                Long time = c.getLong(indtime);
                int position = c.getInt(indposition);
                int sw = c.getInt(indswitch);
                String comm = c.getString(indComment);
                int id = c.getInt(indId);

//build screen
                TimeHelper timeHelper = TimeHelper.getInstance(ctx);
                buildAlarmTable(timeHelper.getTimeStringForDisplay(time),
                        position, sw, comm, id, timeHelper.getAMPM(time));

            } while (c.moveToNext());

            if(c != null)
                c.close();
            if(db != null)
                db.close();
        }
    }

    private void showInfoToast() {
        Toast.makeText(ctx, getResources().getText(R.string.infoToast).toString(),
                Toast.LENGTH_LONG).show();
    }

    //add views in activity
    private void buildAlarmTable(String time, int position, int sw, String comm, int id, String AMPM) {

        SQLiteDatabase db = DbHelper.getReadableDatabase();
        String strRepDays = "";
        try {
            strRepDays = DbHelper.getRepDays(db, id);
        }
        finally {
            if(db != null)
                db.close();
        }

        //Родительский слой - 1 уровень
        LinearLayout parentLayout = new LinearLayout(this);
        parentLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
        parentLayout.setOrientation(LinearLayout.HORIZONTAL);
        parentLayout.setBaselineAligned(false);
        LL.addView(parentLayout);

        //Слой для текстовый полей - 2 уровень
        LinearLayout textFieldLayout = new LinearLayout(this);
        textFieldLayout.setOrientation(LinearLayout.VERTICAL);
        textFieldLayout.setLayoutParams(new LinearLayout.LayoutParams(0,
                LayoutParams.WRAP_CONTENT, 1f));
        textFieldLayout.setPadding(0,0,0,10);
        parentLayout.addView(textFieldLayout);

        //Слой для свичера - 2 уровень
        LinearLayout switcherLayout = new LinearLayout(this);
        switcherLayout.setOrientation(LinearLayout.VERTICAL);
        switcherLayout.setLayoutParams(new LinearLayout.LayoutParams(0,
                LayoutParams.MATCH_PARENT,1f));
        //switcherLayout.setPadding(0,0,20,0);
        parentLayout.addView(switcherLayout);

        //вложим текстовое поле времени в отдельный слой
        LinearLayout timeLayout = new LinearLayout(this);
        timeLayout.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        timeLayout.setOrientation(LinearLayout.HORIZONTAL);
        timeLayout.setGravity(Gravity.CENTER_HORIZONTAL);
        textFieldLayout.addView(timeLayout);


        //Текстовое поле время
        TextView TimeText = new TextView(this);
        TimeText.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        TimeText.setId(id);
        TimeText.setTextColor(Color.WHITE);
        TimeText.setTextSize(40);
        TimeText.setText(time);
        TimeText.setGravity(Gravity.CENTER);
        TimeText.setOnClickListener(this);
        TimeText.setOnLongClickListener(this);
        timeLayout.addView(TimeText);

        //Текстовое поле формата времени
        if(!is24HourFormat){
            TextView formatText = new TextView(this);
            formatText.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            formatText.setTextColor(Color.WHITE);
            formatText.setTextSize(10);
            formatText.setText(AMPM);
            timeLayout.addView(formatText);
        }

        //Поле коментарий
        TextView commentText = new TextView(this);
        commentText.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
        commentText.setTextColor(Color.WHITE);
        commentText.setGravity(Gravity.CENTER);
        commentText.setTextSize(15);
        if (comm.length() == 0){
            commentText.setText(getString(R.string.Alarm) +" "+ position);
        }
        else{
            commentText.setText(comm);
        }
        textFieldLayout.addView(commentText);

        //Добавляем слой для повторов с раскашиванием
        LinearLayout repLay = new LinearLayout(this);
        repLay.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        repLay.setOrientation(LinearLayout.HORIZONTAL);
        repLay.setGravity(Gravity.CENTER);
        textFieldLayout.addView(repLay);

        //Текствовые поля дней недели
        TextView monTxt = new TextView(this);
        monTxt.setText(Util.getInstance(ctx).createRepDaysString(strRepDays));
        monTxt.setTextSize(10);
        monTxt.setTextColor(Color.WHITE);
        monTxt.setGravity(Gravity.CENTER);
        monTxt.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        repLay.addView(monTxt);

        //Чек бокс
        CheckBox chk = new CheckBox(this);
        chk.setId(1000+id);
        chk.setText("");
        if (sw == 1){
            chk.setChecked(true);
        }
        else {
            chk.setChecked(false);
        }
        //кастом чек бокс
        chk.setButtonDrawable(R.drawable.sw_states);
        chk.setOnClickListener(this);
        chk.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        chk.setMinWidth(200);
        chk.setPadding(0,70,0,0);
        switcherLayout.addView(chk);

        //Черта
        View vv = new View(this);
        vv.setBackgroundColor(Color.rgb(0xc0, 0xc0, 0xc0));
        LayoutParams lpvv = new LayoutParams(LayoutParams.MATCH_PARENT, 1);
        vv.setLayoutParams(lpvv);
        vv.setBackgroundResource(R.drawable.main_activity_separator);
        LL.addView(vv);
    }

    @Override
    protected void onResume() {
        super.onResume();

        Util.getInstance(ctx).setTheme(llParent);

        SQLiteDatabase db = DbHelper.getWritableDatabase();

        try{
            Cursor c = DbHelper.getAlarms(db);
            if(c.getCount() == 0 && Util.getInstance(ctx).androidVersionCode() <= 2){
                showInfoToast();
            }
            c.close();
        }
        finally {
            if(db != null)
                db.close();
        }

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        boolean hold = sp.getBoolean("hold", false);
        boolean classic = sp.getBoolean("classicOff",true);

        if(!classic){
            if(hold && TimeHelper.getInstance(this).currentRepeat <= 1 && Constants.getInstance(this).alarmed){
                finish();
            }
            else {
                if(Constants.getInstance(this).alarmed && hold){
                    Intent cancelAlarm = Util.getInstance(this).getActualCancelAlarmIntent();
                    cancelAlarm.putExtra("id", Constants.getInstance(this).alarmedID);
                    cancelAlarm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(cancelAlarm);
                    finish();

                }
            }
        }

        clearActivity();
        fillAlarmTable();
    }

    //clear activity
    private void clearActivity(){
        if (null != LL && LL.getChildCount() > 0) {
            try {
                LL.removeViews (0, LL.getChildCount());
            } catch (Exception e) {
                Log.e(LOG_TAG, "Error while clear main activity", e);
            }
        }
    }

    @Override
    public boolean onLongClick(final View view) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.DelAlarm);

        builder.setPositiveButton(R.string.btAdd, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked OK button
                deleteAlarm(view.getId());
            }
        });
        builder.setNegativeButton(R.string.btCancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User cancelled the dialog
            }
        });
        AlertDialog AD = builder.create();
        AD.show();
        return true;
    }

    //delete existing alarm, rebuild activity
    private void deleteAlarm(int id){

        SQLiteDatabase db = DbHelper.getWritableDatabase();
        try{
            DbHelper.deleteAlarm(db,id);
        }
        finally {
            if(db != null)
                db.close();
        }

        operationsToOffAlarm(id);
        clearActivity();
        fillAlarmTable();
    }

    private void operationsToOnAlarm(long actTime, int id){
        Util.getInstance(ctx).operationsToOnAlarm(actTime,id);
    }

    private void operationsToOffAlarm(int id) {
        Util.getInstance(ctx).operationsToOffAlarm(id);
    }

}
